package com.lucy.dingding.core;

import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lucy.common.redis.RedisCache;
import com.lucy.dingding.constant.DingAppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author kindear
 * 钉钉TOKEN管理
 */
@Slf4j
@Service
public class DingAppToken {
    @Resource
    DingOpenApi openApi;

    @Autowired
    RedisCache redisCache;

    public String get(){
        return get(DingAppConfig.appKey,DingAppConfig.appSecret);
    }

    public String get(String appKey,String appSecret){
        String dingToken = redisCache.getCacheObject(DingAppConfig.tokenKey);
        if (Validator.isNotEmpty(dingToken)){
            return dingToken;
        }
        String tokenRes = openApi.exToken(appKey,appSecret);
        JSONObject jsonObject = JSONUtil.parseObj(tokenRes);
        dingToken = jsonObject.getStr("accessToken");
        redisCache.setCacheObject(DingAppConfig.tokenKey, dingToken, DingAppConfig.expireMin, TimeUnit.MINUTES);
        return dingToken;
    }
}
